package net.gianrishandy.jbase.component.support;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JTextField;

import net.gianrishandy.jbase.component.listener.LookupCellListener;

/**
 * @author Gian Rishandy
 *
 */
public class LookupCell extends JTextField {
	
	private static final long serialVersionUID = 6402063301171479089L;
	private JButton button;
	
	public LookupCell() {
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_F2){
					userLookupCellListener();
				}
			}
		});
		setPreferredSize(new Dimension(220, 20));
		setLayout(new BorderLayout());
		
		button = new JButton("...");
		button.setPreferredSize(new Dimension(23, 20));
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				userLookupCellListener();
			}
		});
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			}
			@Override
			public void mouseExited(MouseEvent e) {
				setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
			}
		});
		
		add(button, BorderLayout.EAST);
	}

	public void addLookupCellListener(LookupCellListener listener){
		listenerList.add(LookupCellListener.class, listener);
	}
	
	public void removeLookupCellListener(LookupCellListener listener){
		listenerList.remove(LookupCellListener.class, listener);
	}
	
	private void userLookupCellListener(){
		Object[] list = listenerList.getListenerList();
		for(int i=0;i<list.length;i+=2){
			if(list[i] == LookupCellListener.class){
				((LookupCellListener)list[i+1]).lookupCellActionPerformed();
			}
		}
	}
}
